package com.itheima.atte.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.common.util.JsonUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

public class BMapUtil {


    private static final String AK = "EnfvBtgZXLCSEtiawSZf6nDanS84Rpru";

    // 调用百度地图API根据地址，获取坐标
    public static Map<String, BigDecimal> getCoordinate(String address) throws IOException {
        HashMap<String, BigDecimal> objectObjectHashMap = new HashMap<>();
        if (address != null && !"".equals(address)) {
            address = address.replaceAll("\\s*", "").replace("#", "栋");
            String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak=" + AK;
            String json = loadJSON(url);
            Map<?, ?> stringStringMap = JsonUtils.toMap(json, Object.class, Object.class);
            JsonNode resultNode = new ObjectMapper().readTree(json);
            JsonNode status = resultNode.get("status");
            if ("0".equals(status.asText())) {
                JsonNode result = resultNode.get("result");
                JsonNode location1 = result.get("location");
                JsonNode lng = location1.get("lng");
                JsonNode lat = location1.get("lat");
                objectObjectHashMap.put("lng", new BigDecimal(lng.asDouble()));
                objectObjectHashMap.put("lat", new BigDecimal(lat.asDouble()));
            }
        }
        return objectObjectHashMap;
    }

    public static String loadJSON(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json.toString();
    }

    public static void main(String[] args) throws IOException {
        Map<String, BigDecimal> coordinate = getCoordinate("天津互联网教育大厦");
        System.out.println(coordinate);
    }
}
